import datetime
import time


def get_time(format_flag=1, format_ms=1, format_str="", to_string=1) -> str:
    """
    get now timeString or timeStamp
    获取当前时间字符串或时间戳（默认返回%Y-%m-%d %H:%M:%S格式的日期字符串）
    :param format_flag: 0返回时间戳，1返回日期，默认值1
    :param to_string: 0返回日期类型，1返回字符串，默认值1
    :param format_ms: 0返回精确到微秒，1不精确到微秒，默认值1
    :param format_str: 格式化字符串，不传取默认值
    :return:
    """
    """
    eg: time_utils.get_time(0, 0)  # 获取当前秒数，精确到小数后六位  # 1695715135.357394
    eg: time_utils.get_time(0)  # 获取当前秒数，精确到秒  # 1695715135
    eg: time_utils.get_time(format_ms=0, format_str="%Y%m%d-%H%M%S")  # 获取当前日期字符串，格式为 %Y%m%d-%H%M%S.%f
    eg: time_utils.get_time(format_str="%Y%m%d-%H%M%S-%f")  # 获取当前日期字符串，格式为 %Y%m%d-%H%M%S.%f
    eg: time_utils.get_time(to_string=False)  # 获取当前时间，返回日期类型
    """
    if format_flag:
        if to_string:
            return datetime.datetime.now().strftime(f'{format_str if format_str else "%Y-%m-%d %H:%M:%S"}{"" if format_ms else r".%f"}')
        else:
            return datetime.datetime.now()
    else:
        ft = time.time()
        return int(ft) if format_ms else ft


def to_time_stamp(time_string):
    """
    timeString to timeStamp
    时间字符串转时间戳（有无微秒都可）
    :param time_string:
    :return:
    """
    if '.' not in time_string:
        get_ms = False
    else:
        get_ms = True
    time_tuple = datetime.datetime.strptime(time_string, f'%Y-%m-%d %H:%M:%S{r".%f" if get_ms else ""}')
    ft = float(f'{str(int(time.mktime(time_tuple.timetuple())))}' + (f'.{time_tuple.microsecond}' if get_ms else ''))
    return ft if get_ms else int(ft)


def to_time_string(time_stamp):
    """
    timeStamp to timeString
    时间戳转时间字符串
    :param time_stamp:
    :return:
    """
    if type(time_stamp) == int:
        get_ms = False
    else:
        get_ms = True
    time_tuple = datetime.datetime.utcfromtimestamp(time_stamp + 8 * 3600)
    return time_tuple.strftime(f'%Y-%m-%d %H:%M:%S{r".%f" if get_ms else ""}')


def get_days_after(days: int = 0, date='', format_str=''):
    '''
    获取往后N天之后的时间
    :param days: 往后N天，0为当天，负数为往前N天，默认为当天
    :param date: 指定基准日期，默认为当天
    :param format_str: 返回日期的格式，默认为'%Y-%m-%d %H:%M:%S'
    :return:
    '''
    if not format_str:
        format_str = '%Y-%m-%d %H:%M:%S'
    if not date:
        date_obj = datetime.datetime.today()
    else:
        date_obj = datetime.datetime.strptime(date, format_str)
    date = (date_obj + datetime.timedelta(days=days)).strftime(format_str)
    return date


def get_date_current_week(*weeks, date=None, str_format=1, format='%Y-%m-%d', skip_today=0) -> list:
    """
    获取未来七天的周几的日期
    eg:
      dates = get_date_current_week('Saturday', 'Sunday', date='2023-09-02')  # ['2023-09-08', '2023-09-03']
      dates = get_date_current_week('Saturday', 'Sunday')  # ['2023-09-02', '2023-09-03'],(当天是2023-08-31)
    :param weeks:周几
    :param date:日期，默认当天
    :param str_format: 是否格式化为字符串，默认格式化
    :param format:格式化字符串
    :param skip_today: 是否跳过当天，不跳过当天是取一周八天，默认不跳过
    :return:
    """
    if date:
        date = datetime.datetime.strptime(date, format)
    else:
        date = datetime.date.today()
    dates = []
    if weeks:
        weeks_list = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
        week_start = date.weekday()  # 0-6
        for week in weeks:
            week = weeks_list.index(week)
            if not week:
                print(f"时间输入有误:{week}")
                continue

            if week == week_start:
                if not skip_today:  # 是否需要当天
                    target = date + datetime.timedelta(days=(week-week_start))
                    dates.append(target.strftime(format) if str_format else target)
            if week > week_start:
                # 目标时间大于当前时间，加上日期的差值即可
                target = date + datetime.timedelta(days=(week-week_start))
            else:
                # 目标时间小于或等于当前时间，加上本周剩余时间再加上目标时间
                target = date + datetime.timedelta(days=(7-week_start+week))
            dates.append(target.strftime(format) if str_format else target)
    return dates
